package com.csust.cg.mongodb.contorller;

import com.csust.cg.mongodb.domain.HttpStatus;
import com.csust.cg.mongodb.domain.Result;
import com.csust.cg.mongodb.domain.vo.ConnectionVO;
import com.csust.cg.mongodb.service.ConnectService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author chenguang
 */
@RequestMapping("/api")
@RestController
@ResponseBody
public class ConnectController {

    @Autowired
    private ConnectService connectService;

    @PostMapping("connect")
    public Result connect(@Validated ConnectionVO connection, HttpServletRequest request) {
        String token = request.getHeader("u-token");
        if (connection == null) {
            return new Result("连接信息为空!", HttpStatus.BAD_REQUEST);
        }
        if (StringUtils.isNotBlank(connection.getAuthMechanism())) {
            if ((StringUtils.isBlank(connection.getUsername()) || StringUtils.isBlank(connection.getPassword()))) {
                return new Result("用户名或密码不能为空！", HttpStatus.BAD_REQUEST);
            }
        }
        return connectService.connect(connection, token);
    }

    @PostMapping("disConnect")
    public Result disConnect(@RequestParam String connectionId) {
        if (StringUtils.isBlank(connectionId)) {
            new Result("连接ID不能为空！", HttpStatus.CONNECT_ID_IS_NULL);
        }
        return connectService.disConnect(connectionId);
    }

    @GetMapping("/getConnectInfo")
    public Result getConnectInfo(@RequestParam String connectionId) {
        if (StringUtils.isBlank(connectionId)) {
            new Result("连接ID不能为空！", HttpStatus.CONNECT_ID_IS_NULL);
        }
        return connectService.getConnectInfo(connectionId);
    }
}
